//
//  DoubleExtension.swift
//  xz-app
//
//  Created by chen on 2025/5/6.
//
import Foundation

extension Double {
    func formatMoney() -> String {
        return String(format: truncatingRemainder(dividingBy: 1) == 0 ? "%.0f" : "%.2f", self)
    }
    
    /// 格式化为带千分位分隔符的数字
    func asDecimal(locale: Locale = Locale.current) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.locale = locale
        
        // 设置最大和最小分数位数
        formatter.minimumFractionDigits = self.isInteger ? 0 : 2
        formatter.maximumFractionDigits = 2
        
        if let formattedAmount = formatter.string(from: NSNumber(value: self)) {
            return formattedAmount
        } else {
            return "--"
        }
    }
    
    /// 判断数字是否为整数
    private var isInteger: Bool {
        return self == floor(self)
    }
}
